var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
var qualityObj = convertEnumToObj(qualityList);
var typeObj = convertEnumToObj(typeList);
var materialObj = convertEnumToObj(materialList);
var billObj = convertEnumToObj(billList);
layui.use(['laypage', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;
    $.each(materialList, function (index, val) {
        materialObj[val.id] = val.fullName;
    });
    $(".startTime").datePicker({
        format:"YYYY-MM",
        singleDate:true,  //单选日期
    });
    $(".endTime").datePicker({
        format:"YYYY-MM",
        singleDate:true,  //单选日期
    });
    // $(".update-today").datePicker({
    //     format:"YYYY-MM",
    //     singleDate:true,  //单选日期
    // });

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            // ,{field: 'orgName', title: '公司', width: 90, fixed: 'left', align: 'center',templet:function (val) {
            //     return orgObj[val.orgId];
            // }}
            ,{field: 'code', title: '编码', width:140, align: 'center'}
            ,{field: 'name', title: '名称', width: 140, align: 'center'}
            ,{field: 'linkMan', title: '联系人', width:140, align: 'center'}
            ,{field: 'type', title: '类型', align: 'center',templet:function (val) {
                if (val.type < 0)
                    return '';
                else
                    return typeObj[val.type];
            }}
            ,{field: 'waitTime', title: '过磅等待时间(分)', width: 100, align: 'center'}
            ,{field: 'startDate', title: '生效时间', width: 120, align: 'center'}
            ,{field: 'endDate', title: '失效时间', width: 120, align: 'center'}
            ,{field: 'signDate', title: '签订时间', width: 120, align: 'center'}
            ,{field: 'status', title: '状态', width:80, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '备注', width: 240, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 150, align:'center', templet:function (val) {
                var str = '';
                if (val.status == 0)
                    str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
                else
                    str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-normal">启用</a>';
                str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">详情</a>';
                return str;
            }}
        ]
    ];

    let windowCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'materialId', title: '材料', width:140, align: 'center', templet:function (val) {
                return materialObj[val.materialId];
            }}
            ,{field: 'price', title: '价格(元)', width:160, align: 'center'}
            ,{field: 'type', title: '类型', width:120, align: 'center',temlet:function (val) {
                return typeObj[val.type];
            }}
            ,{field: 'takeTime', title: '生效时间', width:120, align: 'center'}
            ,{field: 'isBill', title: '是否结算', width:120, align: 'center',temlet:function (val) {
                return billObj[val.isBill];
            }}
            ,{field: 'remark', title: '备注', width:120, align: 'center' }
            ,{field: 'status', title: '状态', width:80, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            // ,{fixed: 'right', title:'操作', width: 220, align:'center', templet:function (val) {
            //     var str = '';
            //     // if (val.status == 0)
            //     //     str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
            //     // else
            //     //     str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-normal">启用</a>';
            //     str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">修改</a>';
            //     str += '<a lay-event="selected" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">选用</a>';
            //     return str;
            // }}
        ]
    ];
    table.render({
        elem: '#body-list'
        ,url: '/main-material-contract/page'
        ,method: 'post'
        ,page: true
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val()
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res)
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要删除？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option = {
                    id: id,
                    status: updateStatus
                };
                save(option, "/main-material-contract/update-status/" + id);
            }, function(index){

            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            $('.addModal').show();
            $('.addModal .detail-code').val(data.code);
            $('.addModal .detail-org').val(orgObj[data.orgId]);
            $('.addModal .detail-name').val(data.name);
            $('.addModal .detail-linkMan').val(data.linkMan);
            $('.addModal .detail-type').val(typeObj[data.type]);
            // $('.updateModal .update-material').val(data.mid);
            $('.addModal .detail-phone').val(data.phone);
            $('.addModal .detail-startDate').val(data.startDate);
            $('.addModal .detail-endDate').val(data.endDate);
            $('.addModal .detail-signDate').val(data.signDate);
            $('.addModal .detail-waitTime').val(data.waitTime);
            $('.addModal .remark').val(data.remark);
            form.render();
            table.render({
                elem: '#window-list'
                ,url: '/main-material-contract/find-price'
                ,method: 'post'
                ,page: false
                ,height:300
                ,cols: windowCols
                ,where: {contractId:data.contractId}
                ,parseData: function(res){ //res 即为原始返回的数据
                    console.log(res)
                    if (res.code == 0 && res.data != null) {
                        return {
                            "code": res.code, //解析接口状态
                            "msg": res.msg, //解析提示文本
                            "count": res.data, //解析数据长度
                            "data": res.data //解析数据列表
                        };
                    } else {
                        return {
                            "code": res.code, //解析接口状态
                            "msg": '没有任何数据', //解析提示文本
                            "count": 0, //解析数据长度
                            "data": '' //解析数据列表
                        };
                    }

                }
            });
        }
    });

    // form.on('select(search-today)', function(data) {
    //     $(".btn-query").trigger("click");
    // });
    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-origin)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-supplier)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-type)', function(data) {
        $(".btn-query").trigger("click");
    });
    $('.btn-query').on('click', function () {//搜索按钮
        var status = $('.search-status').val();
        var searchVal = $('.search-text').val();
        var orgId = $('.search-origin').val();
        var type = $('.search-type').val();
        var supplierId = $('.search-supplier').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(supplierId))
            option['supplierId'] = supplierId;
        if (!isNull(type))
            option['type'] = type;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        console.log(option)
        table.reload('body-list', {
            where: option
        });
    });

    $(".addModal .close").on("click", function() {
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
    });
    // $('.msgModal').on('click', function () {
    //     $(".addModal").hide();
    //     $(".msgModal").hide();
    // });

    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'put',
            dataType: 'json',
            data:option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("更新成功!");
                    table.reload('body-list', { where: {offset: 0,page:1,
                            limit: limit,
                            type:$('.search-type').val(),
                            supplierId:$('.search-supplier').val(),
                            orgId:$('.search-origin').val()} });
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
});